package com.example.itcacp.config;

import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.cors.CorsConfigurationSource;
import java.util.Arrays;
import java.util.List;

/**
 * 配置无状态会话、请求授权规则，并将 JWTInterceptor 整合到 Security 过滤器链中
 * 使用@PreAuthorize("hasRole('ADMIN')")等注解进行方法级权限控制
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Resource
    private JWTInterceptor jwtInterceptor;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                // 配置CORS并使用自定义配置源
                .cors(cors -> cors.configurationSource(corsConfigurationSource()))
                // 禁用CSRF保护（因为使用JWT）
                .csrf(csrf -> csrf.disable())
                // 配置会话管理为无状态
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                // 配置请求授权规则
                .authorizeHttpRequests(authorize -> authorize
                .requestMatchers( HttpMethod.OPTIONS, "/**").permitAll() // 放行所有OPTIONS请求
                .requestMatchers(// 放行指定路径
                        "/api/users/login",
                        "/api/admin/login",
                        "/api/users/register",
                        "/api/contentRecommend",
                        "/api/projectRecommend",
                        "/api/content/**",
                        "/avatar/**",
                        "/content/**",
                        "/temp/**",
                        "/api/uploadImage",
                        "/api/projects/uploadFile/**",
                        "/ws/**", // 放行WebSocket端点
                        "/api/send/**"
                ).permitAll()
                .anyRequest().authenticated() // 其他请求需要认证
                )
                // 添加JWT拦截器到过滤器链
                .addFilterBefore(jwtInterceptor, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

    /**
     * 配置CORS以允许跨域请求
     */
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();

        // 允许域名（示例：http://localhost:8001）
        configuration.addAllowedOriginPattern("*");

        // 允许的HTTP方法
        configuration.setAllowedMethods( List.of ( "*" ) );

        // 允许的请求头，包括自定义的token头
        configuration.setAllowedHeaders(Arrays.asList(
                "Authorization", "Content-Type", "Accept", "Origin", "X-Requested-With", "token"
        ));

        // 暴露给客户端的响应头
        configuration.setExposedHeaders(Arrays.asList("Authorization", "token"));

        // 允许携带凭证（如cookies, authorization headers）
        configuration.setAllowCredentials(true);

        // 预检请求的缓存时间（秒）
        configuration.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}